#!/bin/bash

usage="Usage: ./install.sh $target_dir"

if [ $# -ne 1 ]; then
	echo $usage
else
	target_dir=$1
	if [[ ${target_dir: -1} == "/" ]]; then
		target_dir=${target_dir%?}
	fi
	echo "create target installation directory -> $1"
	mkdir -p $target_dir/zlogs
	
	echo "copy mysql routines and essential files to target directory"
	cp -r scripts share support-files bin $target_dir
	
	echo "rewrite mysql configuration file"
	cp my.cnf new-my.cnf
	#echo ${target_dir//\//\\\/}
	sed -i "s/install_dir/"${target_dir//\//\\\/}"/g" new-my.cnf
	
	echo "copy mysql configuration file to '/etc/'"
	cp new-my.cnf /etc/my.cnf
	
	echo "change ownership of $target_dir to user:mysql"
	chown mysql:mysql -R $target_dir
	
	sleep 2
	echo "initilize mysql server"
	scripts/mysql_install_db --defaults-file=/etc/my.cnf --user=mysql
	
	sleep 2
	echo "Start mysql server"
	$target_dir/bin/mysqld_safe --defaults-file=/etc/my.cnf &
	
	sleep 2
	rm -rf my-new.cnf new-my.cnf
fi